package com.oren.proxy;


import com.oren.annotation.WswTransaction;
import com.oren.config.DatabaseHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Member;
import java.lang.reflect.Method;

/**
 * @author wsw
 * @time 2018/7/9 22:09
 * @description 事务代理
 * @Since jdk1.7
 */
public class TransactionProxy implements Proxy {

	private final static Logger LOGGER= LoggerFactory.getLogger(TransactionProxy.class);

	private static final ThreadLocal<Boolean> FLAY_HOLDER=new ThreadLocal<Boolean>(){
		@Override
		protected Boolean initialValue() {
			return false;
		}
	};



	public Object doProxy(ProxyChain proxyChain) throws Throwable {
		Object result;
		boolean flag=FLAY_HOLDER.get();
		//拿到目标方法
		Method method=proxyChain.getTargetMethod();
		//是否包含事务注解
		if(!flag && method.isAnnotationPresent(WswTransaction.class)){
			FLAY_HOLDER.set(true);
			try {
				DatabaseHelper.beginTransaction();
				LOGGER.debug("begin transaction ");
				result=proxyChain.doProxyChain();
				DatabaseHelper.commitTransaction();
				LOGGER.debug("commit transaction");
			}catch (Exception e){
				DatabaseHelper.rollbackTransaction();
				LOGGER.debug("rollback transaction ");
				throw  e;
			}finally {
				FLAY_HOLDER.remove();
			}
		}else {
			result=proxyChain.doProxyChain();
		}
		return result;
	}
}
